#!/usr/bin/env python3

import sys
import os
import re
import time

counter = 0
start = time.perf_counter()
total_length = 50


def change_file(path, symbol, dest_symbol):
    global counter
    for root, dirs, files in os.walk(path, topdown=True):
        for name in files:
            if name.endswith('.c') or name.endswith('.h'):
                fname = os.path.join(root, name)
                fin = open(fname, "rt")
                alllines = fin.readlines()
                fin.close()
                fout = open(fname, "w+")
                for line in alllines:
                        # replacing the string and write to output file
                      a = re.sub(symbol, dest_symbol, line)
                      fout.writelines(a)
                fout.close()
                counter += 1
                show_progress()


def count_files_in_directory(directory, topdown=True):
    total_files = 0
    for root, dirs, files in os.walk(directory):
        for fname in files:
            if fname.endswith('.c') or fname.endswith('.h'):
                total_files += 1
    return total_files


def show_progress():
    processed = int(float(counter / totol_files) * total_length)
    unprocess = total_length - processed
    a = "*" * processed
    b = "." * unprocess
    c = (counter / totol_files) * 100
    dur = time.perf_counter() - start
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c, a, b, dur), end = "")

if __name__ == "__main__":
    path = sys.argv[1]
    os.chdir(path)
    print(f"Start to change file in {path}")
    totol_files = count_files_in_directory(path) * 2
    #change_file(path, '__', 'aa')
    change_file(path, '->', 'bb')
    print(f"\nChange file in {path} finished.\n")
